package com.dreamana.components
{
	import com.dreamana.ui.BaseComponent;
	import com.dreamana.ui.ISkinnable;
	import com.dreamana.ui.SkinGraphics;
	
	import flash.display.BitmapData;
	import flash.display.Graphics;
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Matrix;
	import flash.geom.Rectangle;
	
	public class Canvas extends BaseComponent implements ISkinnable
	{
		protected var _back:Shape;
		protected var _backColor:int = -1;
		protected var _backTexture:BitmapData;
		protected var _backRepeat:Boolean = false;
		protected var _backMatrix:Matrix = new Matrix();
		
		public function Canvas(w:int, h:int)
		{
			_width = w;
			_height = h;
			
			this.init();
		}
		
		override protected function addChildren():void
		{
			_back = new Shape();
			this.addChild(_back);
		}
		
		//--- PUBLIC METHODS ---
		
		override public function draw():void
		{
			var g:Graphics = _back.graphics;
			
			g.clear();
			
			if(_backTexture) {
				if(_backRepeat) {
					SkinGraphics.fillRect(g, _backTexture, _width, _height, _backMatrix);
				}
				else {
					//block( keep this bounds size right)
					if(_backColor >= 0) SkinGraphics.drawBlank(g, _width, _height, _backColor);
					else g.drawRect(0, 0, _width, _height);
										
					//clipping
					var bounds:Rectangle = new Rectangle(0, 0, _width, _height);
					var rect:Rectangle = new Rectangle(_backMatrix.tx, _backMatrix.ty, _backTexture.width, _backTexture.height);
					var clip:Rectangle = rect.intersection(bounds);
					
					g.beginBitmapFill(_backTexture, _backMatrix, false);
					g.drawRect(clip.x, clip.y, clip.width, clip.height);
					g.endFill();
				}
			}
			else if(_backColor >= 0) {
				SkinGraphics.drawBlank(g, _width, _height, _backColor);
			}
			else {
				SkinGraphics.drawWireFrame(g, _width, _height);
			}
		}
		
		override public function setStyle(style:String, value:Object):void
		{
			super.setStyle(style, value);
			
			switch(style) {
				case "background-color":
					_backColor = value as Number;
					invalidate();
					break;
				case "background-image":
					_backTexture = value as BitmapData;
					invalidate();
					break;
				case "background-repeat":
					_backRepeat = value as Boolean;
					invalidate();
					break;
				case "background-position":
					if(value.hasOwnProperty("x")) _backMatrix.tx = value.x;
					if(value.hasOwnProperty("y")) _backMatrix.ty = value.y;
					invalidate();
					break;
			}
		}
		
		//--- EVENT HANDLERS ---
		
		
		//--- GETTER/SETTERS ---
		public function get background():Shape { return _back; }
	}
}